#!/bin/bash
# Geolocation Information Retrieval Script
# Function: Get user's geographical location information, showing province for China, country for others

# Set up error handling
exit_on_error() {
    echo "Error: $1" >&2
    exit 1
}

# Check required tools
check_requirements() {
    if ! command -v curl &> /dev/null; then
        exit_on_error "curl command not found, please install curl first"
    fi
    
    if ! command -v jq &> /dev/null; then
        echo "Warning: jq command not found, will use sed and grep to parse JSON"
        USE_JQ=false
    else
        USE_JQ=true
    fi
}

# Get geolocation information
get_location() {
    local api_url="http://ip-api.com/json?lang=en"
    local response
    
    echo "Retrieving geolocation information..."
    
    # Send request with timeout
    response=$(curl -s -m 10 "$api_url")
    
    # Check if request was successful
    if [ $? -ne 0 ]; then
        exit_on_error "Network request failed, please check your network connection"
    fi
    
    # Check API return status
    if $USE_JQ; then
        local status=$(echo "$response" | jq -r '.status')
        if [ "$status" != "success" ]; then
            local message=$(echo "$response" | jq -r '.message')
            exit_on_error "API returned error: $message"
        fi
        
        # Get country and region information
        local country=$(echo "$response" | jq -r '.country')
        local region=$(echo "$response" | jq -r '.regionName')
    else
        # Alternative parsing method (without jq)
        if echo "$response" | grep -q '"status":"success"'; then
            local country=$(echo "$response" | sed -n 's/.*"country":"\([^"]*\)".*/\1/p')
            local region=$(echo "$response" | sed -n 's/.*"regionName":"\([^"]*\)".*/\1/p')
        else
            local message=$(echo "$response" | sed -n 's/.*"message":"\([^"]*\)".*/\1/p')
            exit_on_error "API returned error: $message"
        fi
    fi
    
    # Determine if in China and output appropriate information
    if [ "$country" == "China" ]; then
        if [ -n "$region" ] && [ "$region" != "null" ]; then
            echo "You are currently located in: China $region"
        else
            echo "You are currently located in: China (province information unavailable)"
        fi
    else
        if [ -n "$country" ] && [ "$country" != "null" ]; then
            echo "You are currently located in: $country"
        else
            exit_on_error "Unable to retrieve country information"
        fi
    fi
}

# Main function
main() {
    check_requirements
    get_location
    
    # Add pause mechanism to ensure user has enough time to read results
    echo ""
    echo "----------------------------------------"
    echo "Press any key to continue..."
    read -r -n 1 -s  # Silently read single character input
    
    return 0
}

# Execute main function
main